package com.kingdee.shr.custom.handler.atsexception;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.entity.SelectorItemInfo;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.bos.workflow.WfException;
import com.kingdee.bos.workflow.service.EnactmentServiceProxy;
import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.basedata.org.IPositionMember;
import com.kingdee.eas.basedata.org.PositionInfo;
import com.kingdee.eas.basedata.org.PositionMemberCollection;
import com.kingdee.eas.basedata.org.PositionMemberFactory;
import com.kingdee.eas.basedata.org.PositionMemberInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.atsexc.AtsExceptionBillFactory;
import com.kingdee.eas.custom.atsexc.AtsExceptionBillInfo;
import com.kingdee.eas.custom.atsexc.IAtsExceptionBill;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.eas.hr.base.HRBillStateEnum;
import com.kingdee.eas.util.app.ContextUtil;
import com.kingdee.shr.base.syssetting.app.filter.HRFilterUtils;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import com.kingdee.shr.base.syssetting.web.handler.EditHandler;
import com.kingdee.shr.base.syssetting.web.json.JSONUtils;
import com.kingdee.util.DateTimeUtils;
import com.kingdee.util.StringUtils;

/**
 * @Copyright 版权所有：天津金蝶软件有限公司 <br>
 *            Title: EnrollControllerBean <br>
 *            Description: 考勤异常单-Web端
 * @author yacong_liu Email:yacong_liu@kingdee.com
 * @date 2019-07-31
 * @since V1.0
 */
public class AtsExceptionBillEditHandler extends EditHandler {
	private static Logger logger = Logger
			.getLogger(com.kingdee.shr.custom.handler.atsexception.AtsExceptionBillEditHandler.class);

	private Context ctx;

	private IPositionMember iPositionMember;

	public AtsExceptionBillEditHandler(Context ctx) {
		this.ctx = ctx;
	}

	public AtsExceptionBillEditHandler() {
		this.ctx = SHRContext.getInstance().getContext();
	}

	/**
	 * 
	 * <p>
	 * Title: getOrgInfoAction
	 * </p>
	 * <p>
	 * Description: 获取员工部门信息
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @param modelMap
	 * @throws SHRWebException
	 */
	public void getOrgInfoAction(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap)
			throws SHRWebException {

		String personId = request.getParameter("personId");

		if (StringUtils.isEmpty(personId)) {
			throw new ShrWebBizException("员工为空！");
		}

		try {
			getPositionMemberInterface();
			PositionMemberCollection coll = iPositionMember
					.getPositionMemberCollection(getEntityViewInfo(personId));

			if (coll != null && coll.size() > 0) {
				Map<String, HashMap<String, String>> map = new HashMap<String, HashMap<String, String>>(
						2);
				HashMap<String, String> personF7Map = new HashMap<String, String>(
						2);

				PositionMemberInfo positionMemberInfo = coll.get(0);
				PositionInfo positionInfo = positionMemberInfo.getPosition();

				personF7Map.put("name", convertObjectToString(positionInfo
						.getAdminOrgUnit().getName()));
				personF7Map.put("id", convertObjectToString(positionInfo
						.getAdminOrgUnit().getId()));

				map.put("person", personF7Map);

				writeSuccessData(map);
			}

		} catch (BOSException e) {
			logger.error(e.getMessage(), e);
			throw new SHRWebException("获取部门信息失败！");
		}

	}

	@SuppressWarnings("unchecked")
	public void canSubmitEffectAction(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap)
			throws SHRWebException {
		Map map = new HashMap();
		map.put("state", "success");
		JSONUtils.writeJson(response, map);

	}

	/**
	 * 提交生效
	 * 
	 * @description
	 *@params
	 *@return
	 */
	public void submitEffectAction(HttpServletRequest req,
			HttpServletResponse res, ModelMap modelMap) throws SHRWebException {

		CoreBaseInfo model = (CoreBaseInfo) req.getAttribute("dynamic_model");
		try {
			IAtsExceptionBill IAtsExceptionBill = AtsExceptionBillFactory
					.getRemoteInstance();
			IObjectPK objectPK = IAtsExceptionBill.submitEffect(model);
			model.setId(BOSUuid.read(objectPK.toString()));
		} catch (EASBizException e) {
			throw new SHRWebException(e.getMessage());
		} catch (Exception e) {
			throw new ShrWebBizException(e.getMessage());
		}

		System.out.println("考勤异常单id：" + model.getId().toString());

		writeSuccessData(model.getId().toString());
	}

	@Override
	protected void beforeSave(HttpServletRequest request,
			HttpServletResponse response, CoreBaseInfo model)
			throws SHRWebException {
		super.beforeSave(request, response, model);
		AtsExceptionBillInfo bill = (AtsExceptionBillInfo) model;
		bill.setBillState(HRBillStateEnum.SAVED);
	}

	@Override
	protected void beforeSubmit(HttpServletRequest request,
			HttpServletResponse response, CoreBaseInfo model)
			throws SHRWebException {
		super.beforeSubmit(request, response, model);

		AtsExceptionBillInfo bill = (AtsExceptionBillInfo) model;

		String userID = HRFilterUtils.getCurrentUserId(ctx);
		String functionName = "com.kingdee.eas.custom.atsexc.app.AtsExceptionBillEditUIFunction";
		String operationName = "actionSubmit";
		try {
			String temp = EnactmentServiceProxy.getEnacementService(ctx)
					.findSubmitProcDef(userID, bill, functionName,
							operationName);
			if ((temp == null) || (temp.trim().equals("")))
				throw new ShrWebBizException("没有可用的考勤异常单工作流");
		} catch (WfException e) {
			throw new SHRWebException(e.getMessage());
		} catch (BOSException e) {
			throw new SHRWebException(e.getMessage());
		}

		bill.setBillState(HRBillStateEnum.SUBMITED);
		String operateStatus = request.getParameter("operateState");
		if ((StringUtils.isEmpty(operateStatus))
				|| (!("ADDNEW".equalsIgnoreCase(operateStatus)))) {
			return;
		}
		bill.setExtendedProperty("isAddNew", "isAddNew");
	}

	/**
	 * （非 Javadoc）
	 * <p>
	 * Title: afterCreateNewModel
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @param coreBaseInfo
	 * @throws SHRWebException
	 * @see com.kingdee.shr.base.syssetting.web.handler.EditHandler#afterCreateNewModel(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse,
	 *      com.kingdee.eas.framework.CoreBaseInfo)
	 */
	@Override
	protected void afterCreateNewModel(HttpServletRequest request,
			HttpServletResponse response, CoreBaseInfo coreBaseInfo)
			throws SHRWebException {
		super.afterCreateNewModel(request, response, coreBaseInfo);

		java.util.Date nowDate = DateTimeUtils
				.truncateDate(new java.util.Date());
		UserInfo currentUserInfo = ContextUtil.getCurrentUserInfo(this.ctx);
		AtsExceptionBillInfo info = (AtsExceptionBillInfo) coreBaseInfo;
		info.setCreator(currentUserInfo);
		info.setBizDate(nowDate);
	}

	/**
	 * <p>
	 * Title: getEntityViewInfo
	 * </p>
	 * <p>
	 * Description: 组装查询视图
	 * </p>
	 * 
	 * @param personId
	 * @return
	 */
	private EntityViewInfo getEntityViewInfo(String personId) {
		EntityViewInfo viewInfo = new EntityViewInfo();

		FilterInfo filter = new FilterInfo();
		FilterItemInfo filterItemPerson = new FilterItemInfo("person.id",
				personId.toString());
		// 主要岗位
		FilterItemInfo filterItemPrimary = new FilterItemInfo("isPrimary", "1");

		filter.getFilterItems().add(filterItemPerson);
		filter.getFilterItems().add(filterItemPrimary);
		viewInfo.setFilter(filter);

		viewInfo.getSelector().add(new SelectorItemInfo("id"));
		viewInfo.getSelector().add(new SelectorItemInfo("person.id"));
		viewInfo.getSelector().add(new SelectorItemInfo("person.name"));
		viewInfo.getSelector().add(new SelectorItemInfo("position.id"));
		viewInfo.getSelector().add(new SelectorItemInfo("position.number"));
		viewInfo.getSelector().add(new SelectorItemInfo("position.name"));
		viewInfo.getSelector().add(new SelectorItemInfo("position.job.job"));
		viewInfo.getSelector().add(new SelectorItemInfo("position.job.name"));
		viewInfo.getSelector().add(
				new SelectorItemInfo("position.adminOrgUnit.id"));
		viewInfo.getSelector().add(
				new SelectorItemInfo("position.adminOrgUnit.name"));

		return viewInfo;
	}

	private void getPositionMemberInterface() throws BOSException {
		iPositionMember = (iPositionMember == null) ? PositionMemberFactory
				.getRemoteInstance() : iPositionMember;
	}

	private String convertObjectToString(Object obj) {
		String value = "";
		if (obj != null) {
			value = obj.toString();
		}

		return value;

	}

}
